<template>
  <div class="">
    <!-- head -->
    <el-affix :offset="94">
      <div class="card affix-container pt15 pb14">
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑商品" : "新增商品" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit" type="primary">保存</el-button>
            </div>
          </template>
        </el-page-header>
      </div>
    </el-affix>
    <!-- head end -->
    <div class="card mt10">
      <el-form :model="waresForm" label-width="120px" :rules="couponRules" ref="ruleFormRef">
        <!-- 基础信息 -->
        <div class="group">
          <div class="section-title">基础信息</div>
          <el-form-item label="销售方式" prop="saleType">
            <el-radio-group v-model="waresForm.saleType">
              <el-radio :label="1" border>普通</el-radio>
              <el-radio :label="2" border>称重销售</el-radio>
              <el-radio :label="3" border>按数量销售</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品条码" prop="bn">
            <el-input class="width320" v-model="waresForm.bn" placeholder="请填写" />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input class="width320" v-model="waresForm.name" placeholder="请填写" />
          </el-form-item>
          <el-form-item label="数字助记码" prop="helpCode">
            <el-input class="width320" v-model="waresForm.helpCode" placeholder="请填写" />
          </el-form-item>
          <el-form-item label="拼音助记码" prop="pinYin">
            <el-input class="width320" v-model="waresForm.pinYin" placeholder="请填写" />
          </el-form-item>
          <el-form-item label="商品类别" prop="goodsCategoryId">
            <el-tree-select
              class="width320"
              node-key="value"
              v-model="waresForm.goodsCategoryId"
              :data="waresCategory"
              :render-after-expand="false"
              check-strictly
            />
          </el-form-item>
          <!-- <el-form-item label="商品单位" prop="productsId">
            <el-select class="width320" v-model="waresForm.productsId">
              <el-option
                v-for="audience in promotionalAudience"
                :key="audience.value"
                :label="audience.label"
                :value="audience.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="商品PLU" prop="plu" v-if="waresForm.saleType !== 1">
            <el-input-number class="width320" v-model="waresForm.plu" placeholder="1-6位数字" :controls="false" />
          </el-form-item>
          <el-form-item label="商品品牌" prop="brandId">
            <el-select class="width320" v-model="waresForm.brandId">
              <el-option v-for="brand in brands" :key="brand.id" :label="brand.name" :value="brand.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品封面" prop="image">
            <UploadImg v-model:image-url="waresForm.image" :file-size="3">
              <template #empty>
                <el-icon><Picture /></el-icon>
                <span>请上传封面图</span>
              </template>
              <template #tip> 图片大小不能超过 3M </template>
            </UploadImg>
          </el-form-item>
          <el-form-item label="商品图集" prop="images">
            <UploadImgs v-model:file-list="waresForm.images">
              <template #empty>
                <el-icon><Picture /></el-icon>
                <span>请上传照片</span>
              </template>
              <template #tip> 照片大小不能超过 5M </template>
            </UploadImgs>
          </el-form-item>
        </div>
        <div class="group">
          <div class="section-title">销售信息</div>
          <el-form-item label="商品规格">
            <el-table :data="waresForm.products" size="small" border>
              <el-table-column prop="barcode" label="条形码" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.barcode" placeholder="条形码" />
                </template>
              </el-table-column>
              <el-table-column prop="spesDesc" label="规格名称" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.spesDesc" placeholder="规格名称" />
                </template>
              </el-table-column>
              <el-table-column prop="unitName" label="规格单位" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.unitName" placeholder="规格单位" />
                </template>
              </el-table-column>
              <el-table-column prop="convert" label="转换系数" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.convert" placeholder="转换系数" />
                </template>
              </el-table-column>
              <el-table-column prop="purPrice" label="采购价" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.purPrice" />
                </template>
              </el-table-column>
              <el-table-column prop="posPrice" label="零售价" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.posPrice" />
                </template>
              </el-table-column>
              <el-table-column prop="rmoPrice" label="配送价" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.rmoPrice" />
                </template>
              </el-table-column>
              <el-table-column prop="vip1Price" label="一级会员价" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.vip1Price" />
                </template>
              </el-table-column>
              <el-table-column prop="vip2Price" label="二级会员价" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.vip2Price" />
                </template>
              </el-table-column>
              <el-table-column prop="vip3Price" label="三级会员价" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.vip3Price" />
                </template>
              </el-table-column>
              <el-table-column prop="onLine" label="是否上架" align="center">
                <template #default="scope">
                  <el-switch v-model="scope.row.onLine" size="small" />
                </template>
              </el-table-column>
              <el-table-column prop="operate" label="操作" align="center">
                <template #default="scope">
                  <el-text v-if="scope.$index === 0" type="primary">默认</el-text>
                  <el-button v-else type="danger" size="small" @click="delSpecRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="mt10" type="primary" v-if="waresForm.saleType === 1" @click="addSpec">添加规格</el-button>
          </el-form-item>
        </div>
        <div class="group">
          <div class="section-title">商品详情</div>
          <el-form-item label="" prop="intro">
            <WangEditor v-model:value="waresForm.intro" height="400px" />
          </el-form-item>
        </div>
        <div class="group">
          <div class="section-title">更多信息</div>
          <el-form-item label="货号" prop="articleNo">
            <el-input class="width320" v-model="waresForm.articleNo" placeholder="请填写" />
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-select class="width320" v-model="waresForm.supplierId">
              <el-option v-for="audience in supplierList" :key="audience.id" :label="audience.name" :value="audience.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="组织机构" prop="organizationId">
            <el-select v-model="waresForm.organizationId" placeholder="请选择" class="width320">
              <el-option v-for="category in organization" :key="category.name" :label="category.name" :value="category.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="经营方式" prop="operationMode">
            <el-select class="width320" v-model="waresForm.operationMode">
              <el-option label="购销" :value="1" />
              <el-option label="代销" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="管理库存" prop="isStock">
            <el-radio-group v-model="waresForm.isStock">
              <el-radio :label="true" border>是</el-radio>
              <el-radio :label="false" border>否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有效期" prop="effectiveDays">
            <el-input
              class="width320"
              v-model="waresForm.effectiveDays"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入"
            >
              <template #append>
                <div>天</div>
              </template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="进税项" prop="way">
            <el-input class="width320" v-model="waresForm.way" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入">
              <template #append>
                <div>%</div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="销税项" prop="way">
            <el-input class="width320" v-model="waresForm.way" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入">
              <template #append>
                <div>%</div>
              </template>
            </el-input>
          </el-form-item> -->
          <el-form-item label="产地" prop="producer">
            <el-input class="width320" v-model="waresForm.producer" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="参与折扣" prop="isDiscount">
            <el-radio-group v-model="waresForm.isDiscount">
              <el-radio :label="true" border>参与</el-radio>
              <el-radio :label="false" border>不参与</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="时价商品" prop="isRulingPrice">
            <el-radio-group v-model="waresForm.isRulingPrice">
              <el-radio :label="true" border>否</el-radio>
              <el-radio :label="false" border>是</el-radio>
            </el-radio-group>
            <el-text class="ml10" type="info">说明：在收银机销售时候可以进行实时变价</el-text>
          </el-form-item>
          <el-form-item label="是否积分" prop="isIntegral">
            <el-radio-group v-model="waresForm.isIntegral">
              <el-radio :label="false" border>否</el-radio>
              <el-radio :label="true" border>是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="导购提成" prop="commissionType">
            <el-radio-group v-model="waresForm.commissionType">
              <el-radio :label="1" border>不提成</el-radio>
              <el-radio :label="2" border>按比率</el-radio>
              <el-radio :label="3" border>按金额</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="commissionValue" v-if="waresForm.commissionType !== 1">
            <el-input
              class="width320"
              v-model="waresForm.commissionValue"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入"
            >
              <template #append>
                <div v-if="waresForm.commissionType === 2">%</div>
                <div v-if="waresForm.commissionType === 3">￥</div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input
              class="width400"
              v-model="waresForm.remark"
              :autosize="{ minRows: 4, maxRows: 10 }"
              type="textarea"
              placeholder="请输入内容..."
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts" name="waresEdit">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { editWares, createWares, getEditWares } from "@/api/modules/inventory";
import type { FormInstance } from "element-plus";
import { transformCategories } from "@/utils";
import { getOrganizationList } from "@/api/modules/operation";
import UploadImg from "@/components/Upload/Img.vue";
import UploadImgs from "@/components/Upload/Imgs.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { getWaresBrandList, getWaresCategoryList, getSupplierList } from "@/api/modules/inventory";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);
const waresForm = reactive({
  id: 0,
  saleType: 1,
  bn: "",
  name: "",
  image: "",
  images: [],
  pinYin: "",
  helpCode: "",
  goodsCategoryId: 1,
  brandId: 1,
  articleNo: "",
  plu: "",
  commissionValue: 0,
  organizationId: 0,
  // productsId: 1,
  intro: "",
  effectiveDays: "",
  isStock: true,
  operationMode: 1,
  supplierId: 1,
  producer: "",
  isDiscount: true,
  isRulingPrice: true,
  isIntegral: false,
  commissionType: 1,
  remark: "",
  products: [
    {
      barcode: "",
      spesDesc: "",
      unitName: "",
      convert: 1,
      posPrice: 0,
      purPrice: 0,
      rmoPrice: 0,
      vip1Price: 0,
      vip2Price: 0,
      vip3Price: 0,
      onLine: true
    }
  ]
});
const couponRules = reactive({
  name: [{ required: true, message: "请填写商品名称" }],
  bn: [{ required: true, message: "请填写商品条码" }]
  // image: [{ required: true, message: "请上传商品封面" }],
  // images: [{ required: true, message: "请上传商品图集" }],
  // intro: [{ required: true, message: "商品详情不能为空" }],
  // articleNo: [{ required: true, message: "货号不能为空" }]
});

const addSpec = () => {
  waresForm.products.push({
    barcode: "",
    spesDesc: "",
    unitName: "",
    convert: 1,
    posPrice: 0,
    purPrice: 0,
    rmoPrice: 0,
    vip1Price: 0,
    vip2Price: 0,
    vip3Price: 0,
    onLine: true
  });
};

const delSpecRow = (index: number) => {
  waresForm.products.splice(index, 1);
};

const onSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await editWares(waresForm).then(() => {
          router.push({
            path: "/inventory/waresList",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createWares(waresForm).then(() => {
          router.push({
            path: "/inventory/waresList",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};
const brands = ref([]);
const waresCategory = ref([]);
const supplierList = ref([]);
const organization = ref<any>([]);
onMounted(async () => {
  try {
    const [brand, category, supplier, orz] = await Promise.all([
      getWaresBrandList({ pageNum: 1, pageSize: 9999 }),
      getWaresCategoryList(),
      getSupplierList({ pageNum: 1, pageSize: 9999, supplierCode: 0 }),
      getOrganizationList()
      // useSelectStore().getDic("DiscountType")
    ]);
    brands.value = brand.data.list;
    supplierList.value = supplier.data.list;
    organization.value = orz.data.list;
    waresCategory.value = transformCategories(category.data, "name", "id", true);

    if (route.query.id) {
      isEdit.value = true;
      getEditWares({ id: route.query.id }).then(res => {
        Object.keys(waresForm).forEach(key => {
          if (res.data.hasOwnProperty(key)) {
            waresForm[key] = res.data[key];
          }
        });
      });
    } else {
      waresForm.brandId = brand.data.list[0].id;
      waresForm.goodsCategoryId = waresCategory.value[0].value;
      waresForm.supplierId = supplier.data.list[0].id;
      waresForm.organizationId = orz.data.list[0].id;
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
});
</script>

<style lang="scss" scoped>
.section-title {
  padding-left: 4px;
  margin-bottom: 26px;
  font-size: 14px;
  font-weight: 700;
  line-height: 14px;
  color: #333333;
  border-left: 4px solid var(--el-color-primary);
}
.select-day-in-week-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 638px;
  padding: 12px 14px;
  font-family: PingFangSC-Regular;
  color: #222222;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>
